package com.easy.dn.ui.usercenter.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easy.common.base.BaseActivity;
import com.easy.common.baserx.RxBus;
import com.easy.common.baserx.RxSubscriber;
import com.easy.common.commonutils.ImageLoaderUtils;
import com.easy.common.commonwidget.DnToolbar;
import com.easy.dn.api.Api;
import com.easy.dn.api.ApiConstants;
import com.easy.dn.api.ApiService;
import com.easy.dn.app.AppConstant;
import com.easy.dn.app.GlobalApplication;
import com.easy.dn.bean.ApiModel;
import com.easy.dn.bean.InfoRefreshBean;
import com.easy.dn.bean.UserDataBean;
import com.easy.dn.ui.usercenter.contract.MyInfomationContract;
import com.easy.dn.ui.usercenter.model.MyInfomationModel;
import com.easy.dn.ui.usercenter.presenter.MyInfomationPresenter;
import com.easy.dn.utils.DnUtils;
import com.easy.dn.utils.MapHelper;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.makeramen.roundedimageview.RoundedImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import dn.easy.com.easyto.R;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 我的信息
 */
public class MyInfomationActivity extends BaseActivity<MyInfomationPresenter, MyInfomationModel> implements MyInfomationContract.View {

    public static final int REQUEST_CODE_SELECT = 100;
    @Bind(R.id.toolbar)
    DnToolbar mToolbar;
    @Bind(R.id.iv_headImg)
    RoundedImageView mHeadImg;
    @Bind(R.id.tv_info_nickname)
    TextView mTvInfoNickname;
    @Bind(R.id.relative_nickname)
    RelativeLayout mRelativeNickname;
    @Bind(R.id.phone)
    TextView mPhone;
    @Bind(R.id.relative_phonenumber)
    RelativeLayout mRelativePhonenumber;
    @Bind(R.id.company)
    TextView mCompany;
    @Bind(R.id.relative_company_name)
    RelativeLayout mRelativeCompanyName;
    @Bind(R.id.tv_position)
    TextView mPositionName;
    @Bind(R.id.relative_position_name)
    RelativeLayout mRelativePositionName;
    @Bind(R.id.tv_phone)
    TextView upPass;
    @Bind(R.id.relative_update_pass)
    RelativeLayout mRelativeUpdatePass;
    private UserDataBean bean;

    @Override
    public int getLayoutId() {
        return R.layout.act_my_infomation;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {
        initTitle();
        mToolbar.setMainTitle(R.string.user_center_message);
        loadData();
        RxBus();
    }

    /**
     * 通讯
     */
    private void RxBus() {
        mRxManager.on(AppConstant.INFOREFRESH, new Action1<InfoRefreshBean>() {
            @Override
            public void call(InfoRefreshBean bean) {
                if (bean.getFlag() == 1) {
                    mTvInfoNickname.setText(bean.getContent());
                } else if (bean.getFlag() == 2) {
                    mPositionName.setText(bean.getContent());
                }else if (bean.getFlag()==3){
                    mCompany.setText(bean.getContent());
                }
            }
        });
    }

    private void loadData() {
        Map<String, String> map = MapHelper.getAccessMap();
        mPresenter.getInfoData(map);
    }

    @Override
    public void showLoading(String title) {
    }

    @Override
    public void stopLoading() {
    }

    @Override
    public void showErrorTip(String msg) {
        showShortToast(msg);
    }

    @Override
    public void returnInfoData(UserDataBean bean) {
        this.bean = bean;
        mTvInfoNickname.setText(bean.getNickname());
        mPhone.setText(bean.getPhone());
        mCompany.setText(bean.getCompanyName());
        mPositionName.setText(bean.getPosition());
        ImageLoaderUtils.display(this, mHeadImg, ApiConstants.URL + bean.getHeadImgPath());
    }


    @OnClick({R.id.iv_headImg, R.id.relative_nickname, R.id.relative_phonenumber, R.id.relative_company_name, R.id.relative_position_name, R.id.relative_update_pass})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_headImg://头像
                DnUtils.showCamera(this, getSupportFragmentManager(), 1);
                break;
            case R.id.relative_nickname:
                //昵称
                Bundle bundle = new Bundle();
                bundle.putInt(AppConstant.INFOTITLE, 1);
                bundle.putString(AppConstant.INFODATA, mTvInfoNickname.getText().toString().trim());
                startActivity(UserInfoActivity.class, bundle);
                break;
            case R.id.relative_phonenumber:
                break;
            case R.id.relative_company_name:
                //公司名称
                Bundle bd = new Bundle();
                bd.putInt(AppConstant.INFOTITLE, 3);
                bd.putString(AppConstant.INFODATA, mCompany.getText().toString().trim());
                bd.putString(AppConstant.INFOCOMPANYUIL, bean.getCompanyUrl());
                bd.putString(AppConstant.INFOCOMPANYDES, bean.getCompanyDescription());
                startActivity(CompanyNameActivity.class, bd);
                break;
            case R.id.relative_position_name:
                //职位名称
                Bundle positionBunle = new Bundle();
                positionBunle.putInt(AppConstant.INFOTITLE, 2);
                positionBunle.putString(AppConstant.INFODATA, mPositionName.getText().toString().trim());
                startActivity(UserInfoActivity.class, positionBunle);
                break;
            case R.id.relative_update_pass:
                startActivity(UpdataPassActivity.class);
                break;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ArrayList<ImageItem> images = null;
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    final String imgPath = images.get(0).path;
                    File file = new File(imgPath);

                    //构建body
                    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                            .addFormDataPart("access_token", GlobalApplication.getInstance().getAccessToken())
                            .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                            .build();
                    // 上传头像
                    Api.getInstance().get(ApiService.class).uploadFiles("hr/UploadImg?", requestBody).
                            subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
                            subscribe(new RxSubscriber<ApiModel>(this, true) {
                                @Override
                                protected void _onNext(ApiModel apiModel) {
//                                    UserInfoBean.UserBean userModel = GlobalApplication.getInstance().getUserModel();
//                                    userModel.setImgPath(imgPath);
//                                    GlobalApplication.getInstance().setUserModel(userModel);
                                    InfoRefreshBean bean = new InfoRefreshBean();
                                    bean.setFlag(3);
                                    RxBus.getInstance().post(AppConstant.INFOREFRESH, bean);
                                    ImageLoaderUtils.display(MyInfomationActivity.this, mHeadImg, imgPath);
                                }

                                @Override
                                protected void _onError(String message) {
                                    showShortToast(message);
                                }
                            });
                }
            }
        } else {
        }
    }
}
